﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using BestCode.Creds.Business;
using BestCode.Creds.Entities;
using BestCode.Creds.UI.ViewModel;

namespace BestCode.Creds.UI
{
    /// <summary>
    /// Interaction logic for VwEditLayoutTemplate.xaml
    /// </summary>
    public partial class VwEditLayoutTemplate : UserControl
    {
        public event EventHandler OnCloseControl;
        private VmLayout viewModel;

        public VwEditLayoutTemplate()
        {
            InitializeComponent();}

        public void SetViewModel(Template template)
        {
            viewModel = new VmLayout(template);
            this.DataContext = viewModel;
            dynamicCanvas.ItemsSource = viewModel.Items;
            viewModel.OnSaved += viewModel_OnSaved;
            

            //BitmapImage bmp = new BitmapImage(new Uri(template.FaceImagePath, UriKind.Absolute));

            if(!template.AttachmentId.HasValue)
                throw new Exception("Save template one more time  (Edit > Save) int Template Seccion");

            AttachmentBusiness attachmentBusiness = new AttachmentBusiness();
            var temp = attachmentBusiness.Get(template.AttachmentId.Value);
            BitmapImage bmp = LoadImage(temp.MediaContent);
                
            imgFace.Source = bmp;
            imgFace.Height = bmp.Height;
            imgFace.Width = bmp.Width;

        }

        void viewModel_OnSaved(object sender, EventArgs e)
        {
            dynamicCanvas.ItemsSource = null;
            dynamicCanvas.ItemsSource = viewModel.Items;
        }

        private static BitmapImage LoadImage(byte[] imageData)
        {
            if (imageData == null || imageData.Length == 0) return null;
            var image = new BitmapImage();
            using (var mem = new MemoryStream(imageData))
            {
                mem.Position = 0;
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = null;
                image.StreamSource = mem;
                image.EndInit();
            }
            image.Freeze();
            return image;
        }


    }
}
